package com.plian.system.service.sys.announcements;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.plian.Tools.CollectionUtil;
import com.plian.Tools.TokenUtil;
import com.plian.Tools.Tools;
import com.plian.Tools.UuidUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dao.sys.announcements.AnnouncementsDao;
import com.plian.system.dao.sys.file.FileDao;
import com.plian.system.entity.sys.BehavioralData;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.page.Page;
import com.plian.system.service.sys.behavioral.IBehavioralDataService;
import com.plian.system.service.sys.file.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class AnnouncementsService {
    @Autowired
    AnnouncementsDao announcementsDao;
    @Autowired
    FileService fileService;
    @Autowired
    FileDao fileDao;

    @Autowired
    IBehavioralDataService behavioralDataService;
    /**
     * 保存
     * @param pd
     * @return
     */
    public ObjResult save(PageData pd)  {
        try {
            String id= UuidUtil.get32UUID();
            pd.put("createUser", TokenUtil.getTokenUserId());
            pd.put("createTime",new Date());
            pd.put("id", id);
            announcementsDao.save(pd);
            fileService.saveAll(id, (List<HashMap>) pd.get("list_doc"));
            ObjResult objResult=new ObjResult(CommonCode.SUCCESS);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return new ObjResult(CommonCode.ERROR);
        }
    }

    /**
     * 修改
     * @param pd
     * @return
     */
    public ObjResult edit(PageData pd){
        try {
            announcementsDao.edit(pd);
            fileService.edit(pd.getString("id"),(List<HashMap>) pd.get("list_doc"));
            ObjResult objResult=new ObjResult(CommonCode.SUCCESS);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return new ObjResult(CommonCode.ERROR);
        }
    }

    /**
     * 批量删除
     * @param pd
     * @return
     */
    public ObjResult del_ids(PageData pd){
        try {
            announcementsDao.del_ids((List<String>) pd.get("ids"));
            ObjResult objResult=new ObjResult(CommonCode.SUCCESS);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return new ObjResult(CommonCode.ERROR);
        }
    }
    /**
     * 查询列表
     * @return
     */
    public ListResult listPage(PageData pd) {
        ListResult listResult;
        try {
            pd.put("orgId", TokenUtil.getTokenOrgId());
            Page page=new Page(true,pd);
            List<PageData> list=announcementsDao.listPage(page);
            listResult=new ListResult(CommonCode.SUCCESS);
            if (CollectionUtil.isNotEmpty(list)){
                String orgId = TokenUtil.getTokenOrgId();
                String userId = TokenUtil.getTokenUserId();
                //是否看过
                List<BehavioralData> behavioralDataList= behavioralDataService.list(Wrappers.<BehavioralData>lambdaQuery().eq(BehavioralData::getUserId, userId).eq(BehavioralData::getOrgId, orgId).eq(BehavioralData::getActionType, 1)
                        .eq(BehavioralData::getFormType, FormTypeConstant.SYS_ANNOUNCEMENTS));
                if (CollectionUtil.isNotEmpty(behavioralDataList)){
                    list.forEach(message ->{
                        Optional<BehavioralData> any = behavioralDataList.stream().filter(behavioral -> message.getString("id").equals(behavioral.getFormId())).findAny();
                        if (any.isPresent()){
                            message.put("isLook",1);
                        }else {
                            message.put("isLook",0);
                        }
                    });
                }else {
                    list.forEach(message ->{
                        message.put("isLook",0);
                    });
                }
            }
            listResult.setList(list);
            listResult.setTotal(page.getTotal());

        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            listResult=new ListResult(CommonCode.ERROR);
        }
        return listResult;
    }
    public ObjResult findid(PageData pd){
        ObjResult objResult;
        String id=pd.getString("id");
        try {
            PageData p=announcementsDao.findId(id);
            List<PageData> l=fileDao.findParentId(id);
            l.forEach(pageData -> {
                pageData.put("itFileName",pageData.getString("fileName"));
                pageData.put("viewFileName",pageData.getString("fileName"));
                String fileName=pageData.getString("fileName");
                //文件后缀
                String fileTyle=fileName.substring(fileName.lastIndexOf("."));
                if (!"pdf".equalsIgnoreCase(fileTyle)){
                    BigDecimal bigDecimal = new BigDecimal(pageData.getString("fileSize"));
                    BigDecimal b = bigDecimal.divide(new BigDecimal("1048576"), 2, BigDecimal.ROUND_HALF_UP);
                    if (b.floatValue() <= 20) {
                        pageData.put("isPrint", true);
                    }else{
                        pageData.put("isPrint", false);
                    }
                }else{
                    pageData.put("isPrint", true);
                }

                if(Tools.notEmpty(fileName)){
                    fileName=fileName.substring(19);
                    pageData.put("fileName",fileName);
                }
            });
            p.put("list_doc",l);
            objResult=new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            objResult=new ObjResult(CommonCode.ERROR);
            return objResult;
        }
    }

    public ObjResult ChagPublishAll(PageData pd){
        try {
            ObjResult objResult=new ObjResult(CommonCode.SUCCESS);
            announcementsDao.ChagPublishAll(pd);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return new ObjResult(CommonCode.ERROR);
        }
    }
    public ObjResult ChagtopAll(PageData pd){
        try {
            ObjResult objResult=new ObjResult(CommonCode.SUCCESS);
            announcementsDao.ChagtopAll(pd);
            return objResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return new ObjResult(CommonCode.ERROR);
        }
    }
}
